package dazuoye;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;

public class FileSCatalogLoader implements SCatalogLoader{
	private ExamScore readExamScore(String line) throws DataFormatException {
        StringTokenizer a = new StringTokenizer(line, "_");
        if (a.countTokens() != 5) {
            throw new DataFormatException(line);
        } else {
            try {
                String str1 = a.nextToken();
                return new ExamScore(a.nextToken(), a.nextToken(), Integer.parseInt(a.nextToken()), a.nextToken());
            } catch (NumberFormatException num) {
                throw new DataFormatException(line);
            }
        }
    }

    private Unistudent readUnistudent(String line) throws DataFormatException {
        StringTokenizer b = new StringTokenizer(line, "_");
        if (b.countTokens() != 9)
    {
            throw new DataFormatException(line);
        } else {
            try {
                String str2 = b.nextToken();
                return new Unistudent(b.nextToken(), b.nextToken(), Integer.parseInt(b.nextToken()), b.nextToken(), b.nextToken(), b.nextToken(), b.nextToken(), b.nextToken());
            } catch (NumberFormatException num) {
                throw new DataFormatException(line);
            }
        }
    }

    private Grastudent readGrastudent(String line) throws DataFormatException {
        StringTokenizer c = new StringTokenizer(line, "_");
        if (c.countTokens() != 9)
    {
            throw new DataFormatException(line);
        } else {
            try {
                String str3 = c.nextToken();
                return new Grastudent(c.nextToken(), c.nextToken(), Integer.parseInt(c.nextToken()), c.nextToken(), c.nextToken(), c.nextToken(), c.nextToken(), c.nextToken());
            } catch (NumberFormatException num) {
                throw new DataFormatException(line);
            }
        }
    }

    public ScoreCatalog loadSCatalog(String filename) throws FileNotFoundException, IOException, DataFormatException {
        ScoreCatalog scata = new ScoreCatalog();
        FileReader file = new FileReader(filename);
        BufferedReader a = new BufferedReader(file);
        String line;
        
        while ((line=a.readLine()) != null) {
            Object obj;
            if (line.startsWith("Unistudent")) {
                obj = this.readUnistudent(line);
            } else if (line.startsWith("Grastudent")) {
                obj = this.readGrastudent(line);
            } else {
                if(!line.startsWith("ExamScore")) {
                    throw new DataFormatException(line);
                }
                    obj = this.readExamScore(line);
                }
                scata.addExamScore((ExamScore) obj);
            }
            a.close();
        file.close();
        return scata;
        }

}
